import 'dart:async';
import 'dart:io';

import 'package:auto_route/auto_route.dart';
import 'package:casdon/app_providers.dart';
import 'package:casdon/auto_router.dart';
import 'package:casdon/build_gen/assets.gen.dart';
import 'package:casdon/core/auth/auth_storage.dart';
import 'package:casdon/modules/home/services/splash_cache_service.dart';

import 'package:flutter/material.dart';

@RoutePage()
class SplashScreen extends StatefulWidget {
  const SplashScreen({super.key});

  @override
  State<StatefulWidget> createState() {
    return _SplashScreenState();
  }
}

class _SplashScreenState extends State<SplashScreen> {
  double _opacity = 0.0;
  CachedSplashEntry? _cachedSplash;
  Timer? _timer;
  int _remainingSeconds = 0;
  bool _navigationTriggered = false;
  bool _isOpeningLink = false;
  bool _cancelAutoNavigation = false;

  @override
  void initState() {
    super.initState();
    _init();
  }

  @override
  void dispose() {
    _timer?.cancel();
    super.dispose();
  }

  Future<void> _init() async {
    await _loadCachedSplash();
    await Future.delayed(const Duration(milliseconds: 100));
    if (!mounted) return;
    setState(() {
      _opacity = 1.0;
    });
    final displaySeconds = (_cachedSplash?.data.duration ?? 2)
        .clamp(1, 10)
        .toInt();
    _startCountdown(displaySeconds);
    await Future.delayed(Duration(seconds: displaySeconds));
    if (!_cancelAutoNavigation) {
      await _goNext();
    }
  }

  @override
  Widget build(BuildContext context) {
    final mediaPadding = MediaQuery.of(context).padding;
    return Scaffold(
      body: SizedBox.expand(
        child: AnimatedOpacity(
          opacity: _opacity,
          duration: const Duration(milliseconds: 800),
          child: GestureDetector(
            behavior: HitTestBehavior.opaque,
            onTap: _handleSplashTap,
            child: Stack(
              fit: StackFit.expand,
              children: [
                _buildSplashImage(),
                Positioned(
                  top: mediaPadding.top + 16,
                  right: mediaPadding.right + 16,
                  child: _buildCountdownBadge(),
                ),
              ],
            ),
          ),
        ),
      ),
    );
  }

  Future<bool> checkLogin() async {
    final storage = getProvider(authStorageProvider.notifier);
    // await storage.clear();
    return await storage.isAuthenticated();
  }

  Future<void> _loadCachedSplash() async {
    final splashCache = getProvider(splashCacheServiceProvider);
    final entries = await splashCache.loadCachedSplashes();
    if (!mounted || entries.isEmpty) return;
    final entryWithImage = entries.firstWhere((entry) {
      final path = entry.localImagePath;
      if (path == null) return false;
      return File(path).existsSync();
    }, orElse: () => entries.first);
    if (!mounted) return;
    setState(() {
      _cachedSplash = entryWithImage;
    });
  }

  Widget _buildSplashImage() {
    final path = _cachedSplash?.localImagePath;
    if (path != null && File(path).existsSync()) {
      return Image.file(File(path), fit: BoxFit.fill);
    }
    return Image.asset(Assets.images.splash.path, fit: BoxFit.fill);
  }

  void _startCountdown(int seconds) {
    _timer?.cancel();
    setState(() {
      _remainingSeconds = seconds;
    });
    _timer = Timer.periodic(const Duration(seconds: 1), (timer) {
      if (!mounted) {
        timer.cancel();
        return;
      }
      if (_remainingSeconds <= 1) {
        timer.cancel();
        setState(() {
          _remainingSeconds = 0;
        });
      } else {
        setState(() {
          _remainingSeconds -= 1;
        });
      }
    });
  }

  Future<void> _goNext() async {
    if (_navigationTriggered) return;
    _navigationTriggered = true;
    _timer?.cancel();
    final loggedIn = await checkLogin();
    if (!mounted) return;
    if (loggedIn) {
      context.router.replaceAll([const TabRoute()]);
    } else {
      context.router.replaceAll([const AccountInputRoute()]);
    }
  }

  Future<void> _handleSplashTap() async {
    if (_isOpeningLink) return;
    final link = _cachedSplash?.data.linkUrl;
    if (link == null || link.trim().isEmpty) {
      return;
    }
    _cancelAutoNavigation = true;
    _timer?.cancel();
    final sanitizedLink = link.trim();
    final normalizedLink = sanitizedLink.startsWith('http')
        ? sanitizedLink
        : 'https://$sanitizedLink';
    _isOpeningLink = true;
    try {
      await _goNext();
    } finally {
      _isOpeningLink = false;
    }
  }

  Widget _buildCountdownBadge() {
    if (_remainingSeconds <= 0) {
      return const SizedBox.shrink();
    }
    return GestureDetector(
      behavior: HitTestBehavior.opaque,
      onTap: () {
        _cancelAutoNavigation = true;
        _goNext();
      },
      child: Container(
        padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 6),
        decoration: BoxDecoration(
          color: Colors.black54,
          borderRadius: BorderRadius.circular(16),
        ),
        child: Text(
          '跳过 ${_remainingSeconds}',
          style: const TextStyle(color: Colors.white, fontSize: 12),
        ),
      ),
    );
  }
}
